<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 顶部搜索框和按钮区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddPage">添加商品</el-button>
        </el-col>
      </el-row>

      <!--  table 表格区域 -->
      <el-table :data="goodsList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column width="95px" label="商品价格(元)" prop="goods_price"></el-table-column>
        <el-table-column width="70px" label="商品重量" prop="goods_weight"></el-table-column>
        <el-table-column width="150px" label="创建时间" prop="add_time">
          <template slot-scope="scope">{{ scope.row.add_time | dateFormat }}</template>
        </el-table-column>
        <el-table-column width="130px" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editGoods(scope.row.goods_id)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeById(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <!-- 编辑商品的对话框 -->
    <el-dialog title="更新商品信息" :visible.sync="editDialogVisible" width="70%" @close="editDialogClose">
      <!-- 表单区域 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px" class="editForm">
        <el-form-item label="商品名称" prop="goods_name" class="form-good-name">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input type="number" v-model="editForm.goods_price"> <template slot="append">￥/元</template></el-input>
        </el-form-item>
        <el-form-item label="商品标识" class="form-small-item">
          <div v-if="editForm.goods_big_logo !== ''">
            <el-badge value="大" class="item">
              <el-tag v-html="editForm.goods_big_logo"></el-tag>
            </el-badge>
          </div>
          <el-badge v-else value="大" class="item">
            <el-tag>暂无</el-tag>
          </el-badge>
          <div v-if="editForm.goods_small_logo !== ''">
            <el-badge value="小" class="item"> <el-tag v-html="editForm.goods_small_logo" type="success" style="margin-left: 30px"></el-tag></el-badge>
          </div>
          <el-badge v-else value="小" class="item">
            <el-tag type="success">暂无</el-tag>
          </el-badge>
        </el-form-item>
        <el-form-item label="审核状态" class="form-small-item">
          <el-tag type="danger" v-if="editForm.goods_state === 0">未通过</el-tag>
          <el-tag type="info" v-else-if="editForm.goods_state === 1">审核中</el-tag>
          <el-tag v-else>已审核</el-tag>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input type="number" v-model="editForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="热销次数" class="form-small-item">
          <span>{{ editForm.hot_mumber }}</span>
        </el-form-item>
        <el-form-item label="促销状态" class="form-small-item">
          <el-switch v-model="editForm.is_promote" disabled></el-switch>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight">
            <el-select v-model="goods_weight_unit" slot="prepend" placeholder="选择单位" style="width: 105px">
              <el-option label="克/g" value="1"></el-option>
              <el-option label="千克/kg" value="2"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="添加时间" class="form-small-item">
          <span>{{ editForm.add_time | dateFormat }}</span>
        </el-form-item>
        <el-form-item label="更新时间" class="form-small-item">
          <span>{{ editForm.upd_time | dateFormat }}</span>
        </el-form-item>
        <el-form-item label="商品信息" class="form-big-item">
          <!-- 以表格形式展示商品参数信息 -->
          <el-table :data="editForm.attrs" border stripe>
            <el-table-column prop="attr_sel" label="参数类别" width="100" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.attr_sel === 'only'">静态属性</el-tag>
                <el-tag v-else type="success">动态参数</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column prop="attr_value" label="参数值"> </el-table-column>
            <el-table-column prop="attr_vals" label="预定义参数值"> </el-table-column>
            <el-table-column prop="add_price" label="浮动价格" width="80" align="center"> </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品介绍" class="form-big-item">
          <p v-html="editForm.goods_introduce"></p>
        </el-form-item>
        <el-form-item label="商品图片" class="editImg form-big-item">
          <!-- 循环显示商品图片 -->
          <el-image :src="item.pics_sma_url" v-for="item in editForm.pics" :key="item.pics_id"> </el-image>
        </el-form-item>
        <el-form-item label="上传图片" class="form-big-item">
          <!-- 上传图片的组件 -->
          <el-upload
            class="upload-demo"
            :action="uploadURL"
            :on-preview="handlePictureCardPreview"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
            :on-remove="removeImgList"
            :headers="headersObj"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 jpg/png 文件，且不超过 2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览图片的弹窗 -->
    <el-dialog :visible.sync="imgDialogVisible">
      <img width="100%" :src="imageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 定义查询参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 商品列表数据
      goodsList: [],
      // 总数据条数
      total: 0,
      // 编辑商品对话框中表单的数据对象
      editForm: {},
      // 控制编辑商品对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑商品表单数据的验证规则对象
      editFormRules: {
        // 商品名称
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        // 商品价格
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        // 商品数量
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        // 商品重量
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }]
      },
      // 图片上传的服务器路径
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的 headers 请求头对象
      headersObj: {
        // 必须要配置请求头才能上传成功
        Authorization: window.sessionStorage.getItem('token')
      },
      // 点击文件上传后的图片的显示路径也是预览图片的显示路径
      imageUrl: '',
      // 控制商品重量的单位,1为克、2为千克
      goods_weight_unit: '',
      // 控制预览图片对话框的显示与隐藏
      imgDialogVisible: false,
      disabled: false
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表数据
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表数据失败！')
      }

      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 监听分页的显示条数发生变化的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 监听分页的页码值发生变化的事件
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum
      this.getGoodsList()
    },
    // 删除商品按钮的点击事件
    async removeById(id) {
      // 首先弹框提示询问是否确定删除
      const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除操作！')
      }

      const { data: res } = await this.$http.delete(`goods/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除商品失败！')

      this.$message.success('删除商品成功！')
      this.getGoodsList()
    },
    // 添加商品按钮的点击事件处理函数
    goAddPage() {
      this.$router.push('/goods/add')
    },
    // 表格中编辑商品按钮的点击事件
    async editGoods(id) {
      const { data: res } = await this.$http.get('goods/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败！')

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑商品对话框中的确定按钮点击事件
    editGoodsSubmit() {
      // 判断用户是否选择了商品重量单位
      if (this.goods_weight_unit === '') return this.$message.error('请选择商品重量的单位！')
      // 判断表单数据是否满足提交条件
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请先完善商品信息!')

        // 先完善请求所需数据
        // 为商品重量添加上单位
        this.editForm.goods_weight = this.goods_weight_unit === '1' ? this.editForm.goods_weight + 'g' : this.editForm.goods_weight + 'kg'
        const { data: res } = await this.$http.put('goods/' + this.editForm.goods_id, this.editForm)
        if (res.meta.status !== 200) return this.$message.error('更新商品信息失败！')
        // 提示成功、刷新页面数据、关闭对话框
        this.$message.success('更新商品信息成功！')
        this.getGoodsList()
      })
      this.editDialogVisible = false
    },
    // 文件上传前的钩子，可以限定支持的文件类型
    beforeImgUpload(file) {
      // isJPGOrPNG 数组是支持的文件类型
      const isJPGOrPNG = ['image/jpeg', 'image/png']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (file.type !== isJPGOrPNG[0] && file.type !== isJPGOrPNG[1]) {
        this.$message.error('上传的图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPGOrPNG && isLt2M
    },
    // 文件上传成功时的钩子
    handleImgSuccess(response) {
      // 1.拼接得到一个图片信息对象
      const picInfo = {
        pic: response.data.tmp_path
      }
      // 2.将图片信息对象 push 到 editForm.pics 中
      this.editForm.pics.push(picInfo)
    },
    // 移除文件事件处理函数参数为上传的文件和文件列表
    removeImgList(file) {
      const removePath = file.response.data.tmp_path
      // 先从文件列表中找到该文件的下标
      const i = this.editForm.pics.findIndex((item) => item.pic === removePath)
      // 使用下标删除该项数据
      this.editForm.pics.splice(i, 1)
    },
    // 预览图片按钮的点击事件
    handlePictureCardPreview(file) {
      this.imageUrl = file.url
      this.imgDialogVisible = true
    },
    // 监听编辑商品对话框的关闭事件
    editDialogClose() {
      this.editForm = []
      this.goods_weight_unit = ''
      this.$refs.editFormRef.resetFields()
    }
  },
  // filters 用于定义局部过滤器
  filters: {}
}
</script>

<style lang="less" scoped>
.editForm {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.form-good-name {
  width: 100% !important;
}
.editForm .el-form-item {
  width: 50%;
}
.editForm .form-big-item {
  width: 100%;
}
.form-small-item {
  width: 25% !important;
}
.editImg {
  width: 100%;
}
.editImg .el-image {
  width: 24%;
  margin: 3px 3px;
  border: 1px solid #eee;
  box-sizing: border-box;
  border-radius: 6px;
}
.el-upload {
  width: 24% !important;
}
.editImg .avatar-uploader:hover {
  border-color: #409eff !important;
}
.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
}
.avatar {
  width: 100%;
  display: block;
}
.editForm .el-form-item img {
  width: 100%;
}
.el-badge {
  margin-left: 20px;
}
</style>
